import { login, mobilelogin, sendCaptcha } from '@/servers/api/userController';
import { LockOutlined, MobileOutlined, UserOutlined } from '@ant-design/icons';
import {
    LoginFormPage,
    ProFormCaptcha,
    ProFormInstance,
    ProFormText,
} from '@ant-design/pro-components';
import {
    FormattedMessage,
    getLocale,
    setLocale,
    useIntl,
    useModel,
} from '@umijs/max';
import { Tabs, message, theme } from 'antd';
import { useEffect, useRef, useState } from 'react';
import Forget from '../user/forget/forget';
import Register from '../user/register/register';
import './login.less';
const Logo = require('@/assets/logo.png');

type LoginType = 'phone' | 'account';

const Login = () => {
    const intl = useIntl();
    const lang = getLocale();
    const [loginType, setLoginType] = useState<LoginType>('account');
    const formRef = useRef<ProFormInstance>();
    const { token } = theme.useToken();
    const [nowPage, setnowPage] = useState('');
    const { setInitialState } = useModel('@@initialState');
    const {  getCityList } = useModel('global');
    const onFinish = async (values: any) => {
        let res;
        if (loginType === 'account') {
            res = await login({ ...values, country: '0' }).catch((e) => {
                message.error(e.msg);
            });
        } else {
            res = await mobilelogin({ ...values }).catch((e) => {
                message.error(e.msg);
            });
        }
        if (res) {
            if (res.data.country === '1') {
                // 中国籍
                setLocale('ru-RU');
            } else {
                setLocale('zh-CN');
            }
            // 存储 token
            localStorage.setItem('token', res.data.token ?? '');
            localStorage.setItem('level', res.data.level ?? '0');
            setInitialState({ user: res.data });
            message.success('登录成功');
            window.location.href = window.location.origin + '/home';
        }
    };
    async function getCode() {
        const mobile = formRef?.current?.getFieldValue('mobile');
        if (!mobile) {
            message.error(intl.formatMessage({ id: '请输入手机号' }));
            throw new Error('获取验证码错误');
        }
        const reg = /^[0-9]{11}$/;
        if (!reg.test(mobile)) {
            message.error(intl.formatMessage({ id: '手机号格式错误' }));
            throw new Error('获取验证码错误');
        }
        const res = await sendCaptcha({
            mobile: mobile,
            event: 'mobilelogin',
        });
    }
    const toRegister = () => {
        setnowPage('register');
    };
    function toForget() {
        setnowPage('forget');
    }
    useEffect(() => {
        getCityList();
    }, []);
    return (
        <div className="content">
            {nowPage === '' && (
                <LoginFormPage
                    formRef={formRef}
                    onFinish={onFinish}
                    backgroundImageUrl="https://mdn.alipayobjects.com/huamei_gcee1x/afts/img/A*y0ZTS6WLwvgAAAAAAAAAAAAADml6AQ/fmt.webp"
                    logo={Logo}
                    title="GLUZ"
                    containerStyle={{
                        // backgroundColor: 'rgba(0, 0, 0,0.65)',
                        backdropFilter: 'blur(4px)',
                    }}
                    subTitle="b2b跨境货物采购平台"
                    submitter={{
                        searchConfig: {
                            submitText: intl.formatMessage({ id: '登录' }),
                        },
                    }}
                >
                    <Tabs
                        centered
                        activeKey={loginType}
                        onChange={(activeKey) =>
                            setLoginType(activeKey as LoginType)
                        }
                    >
                        <Tabs.TabPane
                            key={'account'}
                            tab={intl.formatMessage({ id: '账号密码登录' })}
                        />
                        {lang === 'zh-CN' && (
                            <Tabs.TabPane
                                key={'phone'}
                                tab={intl.formatMessage({ id: '手机快捷登录' })}
                            />
                        )}
                    </Tabs>
                    {loginType === 'account' && (
                        <>
                            <ProFormText
                                name="account"
                                fieldProps={{
                                    size: 'large',
                                    prefix: (
                                        <UserOutlined
                                            style={{
                                                color: token.colorText,
                                            }}
                                            className={'prefixIcon'}
                                        />
                                    ),
                                }}
                                placeholder={intl.formatMessage({
                                    id: '用户名',
                                })}
                                rules={[
                                    {
                                        required: true,
                                        message: intl.formatMessage({
                                            id: '用户名',
                                        }),
                                    },
                                ]}
                            />
                            <ProFormText.Password
                                name="password"
                                fieldProps={{
                                    size: 'large',
                                    prefix: (
                                        <LockOutlined
                                            style={{
                                                color: token.colorText,
                                            }}
                                            className={'prefixIcon'}
                                        />
                                    ),
                                }}
                                placeholder={intl.formatMessage({
                                    id: '请输入密码',
                                })}
                                rules={[
                                    {
                                        required: true,
                                        message: intl.formatMessage({
                                            id: '请输入密码',
                                        }),
                                    },
                                ]}
                            />
                        </>
                    )}
                    {loginType === 'phone' && (
                        <>
                            <ProFormText
                                fieldProps={{
                                    size: 'large',
                                    prefix: (
                                        <MobileOutlined
                                            style={{
                                                color: token.colorText,
                                            }}
                                            className={'prefixIcon'}
                                        />
                                    ),
                                }}
                                name="mobile"
                                placeholder={intl.formatMessage({
                                    id: '手机号',
                                })}
                                rules={[
                                    {
                                        required: true,
                                        message: intl.formatMessage({
                                            id: '请输入手机号',
                                        }),
                                    },
                                    {
                                        pattern: /^[0-9]{11}$/,
                                        message: intl.formatMessage({
                                            id: '手机号格式错误',
                                        }),
                                    },
                                ]}
                            />
                            <ProFormCaptcha
                                fieldProps={{
                                    size: 'large',
                                    prefix: (
                                        <LockOutlined
                                            style={{
                                                color: token.colorText,
                                            }}
                                            className={'prefixIcon'}
                                        />
                                    ),
                                }}
                                captchaProps={{
                                    size: 'large',
                                }}
                                placeholder={intl.formatMessage({
                                    id: '请输入验证码',
                                })}
                                captchaTextRender={(timing, count) => {
                                    if (timing) {
                                        return `${count} ${intl.formatMessage({
                                            id: '获取验证码',
                                        })}`;
                                    }
                                    return intl.formatMessage({
                                        id: '获取验证码',
                                    });
                                }}
                                name="captcha"
                                rules={[
                                    {
                                        required: true,
                                        message: intl.formatMessage({
                                            id: '请输入验证码',
                                        }),
                                    },
                                ]}
                                onGetCaptcha={async () => {
                                    await getCode();
                                }}
                            />
                        </>
                    )}
                    <div style={{ marginBlockEnd: 24 }}>
                        <a onClick={toRegister}>
                            <FormattedMessage id="去注册"></FormattedMessage>
                        </a>
                        <a style={{ float: 'right' }} onClick={toForget}>
                            <FormattedMessage id="忘记密码"></FormattedMessage>
                        </a>
                    </div>
                </LoginFormPage>
            )}
            {nowPage === 'forget' && <Forget setnowPage={setnowPage}></Forget>}
            {nowPage === 'register' && (
                <Register setnowPage={setnowPage}></Register>
            )}
        </div>
    );
};

export default Login;
